package com.audiocn.poster;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.audiocn.Utils.DataBaseHelper;
import com.audiocn.Utils.DataBaseInfo;
import com.audiocn.Utils.NoteSQL;
import com.audiocn.Utils.SortSQL;

/**
 * 修改礼品的页面
 * 
 * @author jsycwangwei
 */
public class PresentEditDC extends Activity {
	// private Context context = getApplicationContext();
	private EditText title, content;
	private Spinner mSort;
	private Button sendButton;
	private int nid = 0;
	private ArrayAdapter<String> adapter;
	private Boolean isEdit;
	private final int Nsave = Menu.FIRST;
	private final int Nlist = Menu.FIRST + 1;
	private final int mClose = Menu.FIRST + 2;

	/** 联系人显示名称 **/
	private static final int PHONES_DISPLAY_NAME_INDEX = 0;

	/** 电话号码 **/
	private static final int PHONES_NUMBER_INDEX = 1;

	/** 联系人的ID **/
	private static final int PHONES_CONTACT_ID_INDEX = 3;

	/** 联系人名称 **/
	private ArrayList<String> mContactsName = new ArrayList<String>();


	ListView mListView = null;
	/**
	 * 初始化联系人列表
	 */
	String contactName = null;
	String phoneNumber = null;
	String contacts = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit);

		nid = getIntent().getIntExtra("dedit", 0);
		isEdit = (nid > 0);

		title = (EditText) findViewById(R.id.mtitle);
		content = (EditText) findViewById(R.id.mcontent);
		sendButton = (Button) this.findViewById(R.id.sendButton);
		sendButton.setTextSize(20);
		sendButton.setTextColor(Color.RED);

		Intent intentFromPosterDC = this.getIntent();
		String mDesc = intentFromPosterDC.getStringExtra("msg");
		String mTitle = intentFromPosterDC.getStringExtra("title");

		if (mTitle == null) {
			mTitle = "礼品：";
		}
		content.setText(mTitle + "\n");
		content.getText().append(mDesc);
		mSort = (Spinner) findViewById(R.id.msort);
		Button btn = (Button) findViewById(R.id.newsort);
		List<String> spinnerlist = new ArrayList<String>();

		ContentResolver resolver = this.getContentResolver();

		// 获取手机联系人

		Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,
				PHONES_PROJECTION, null, null, null);
		if (phoneCursor != null) {

			while (phoneCursor.moveToNext()) {
				// 得到手机号码
				phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
				System.out.println("联系人电话    " + phoneNumber);

				// 当手机号码为空的或者为空字段 跳过当前循环
				if (TextUtils.isEmpty(phoneNumber))
					continue;
				// 得到联系人名称
				contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);

				System.out.println("联系人姓名   " + contactName);

				// 得到联系人ID
				// Long contactid =
				// phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);
				// mContactsName.add(contactName);
				// mContactsNumber.add(phoneNumber);
				SortSQL.insert(this, contactName, phoneNumber);

				// 在spinner中显示的信息
				// contacts = contactName + " @" + phoneNumber;
				spinnerlist.add(contactName);
			}
			phoneCursor.close();
		}
		// DataBaseHelper helper = new DataBaseHelper(this,
		// DataBaseInfo.DB_NAME, null, 1);
		// SQLiteDatabase db = helper.getReadableDatabase();
		// db.close();
		// Cursor sc = SortSQL.select(this);
		// sc.moveToFirst();
		// while (!sc.isAfterLast()) {
		// spinnerlist.add(sc.getString(0));
		// sc.moveToNext();
		// }
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, spinnerlist);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mSort.setAdapter(adapter);

		mSort.setSelected(true);
		mSort.setPrompt("选择你的联系人");
		if (isEdit) {
			setTitle("修改礼品");
			getContent(nid);
		} else
			setTitle("添加一个礼品");

		btn.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				addDialog();
			}
		});

		sendButton.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Uri uri = Uri.parse("smsto:" + phoneNumber);
				Intent it = new Intent(Intent.ACTION_SENDTO, uri);
				it.putExtra("sms_body", "Hello, 我的朋友，给你的惊喜:\n"
						+ title.getText().toString() + "\n"
						+ content.getText().toString());
				
				System.out.println("消息发送完毕！！");
			}
		});
	}

	private void addDialog() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("添加一个礼品接受者");

		/**
		 * 设置文本框的布局
		 */
		LinearLayout l = new LinearLayout(this);
		l.setOrientation(LinearLayout.VERTICAL);
		l.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.FILL_PARENT));
		l.setPadding(5, 4, 5, 10);
		/**
		 * 初始化文本框
		 */
		final EditText input = new EditText(this);
		final EditText inputNumber = new EditText(this);
		final TextView tName = new TextView(this);
		final TextView tPhone = new TextView(this);
		tName.setText("联系人姓名");
		tName.setTextSize(25);
		tName.setTextColor(Color.RED);
		tPhone.setText("联系人手机号码");
		tPhone.setTextSize(25);
		tPhone.setTextColor(Color.RED);
		l.addView(tName);
		l.addView(input);
		l.addView(tPhone);
		l.addView(inputNumber);
		alert.setView(l);

		/**
		 * 保存联系人信息
		 */
		alert.setPositiveButton("确定", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String sort = input.getText().toString();
				String number = inputNumber.getText().toString();
				if (sort.trim().length() > 0 && number.trim().length() > 0)
					addSort(input.getText().toString(), inputNumber.toString());
				else
					Toast.makeText(PresentEditDC.this, "收件人不能为空！",
							Toast.LENGTH_LONG).show();
				dialog.dismiss();
			}
		});
		alert.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		alert.show();
	}

	private void addSort(String sort, String number) {
		DataBaseHelper helper = new DataBaseHelper(this, DataBaseInfo.DB_NAME,
				null, 1);
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor c = db.rawQuery("select * from " + DataBaseInfo.SORT_TABLE
				+ " where " + DataBaseInfo.NOTE_SORT + "='" + sort + "'", null);
		if (c.getCount() > 0)
			Toast.makeText(this, "礼品接收者已经存在！", Toast.LENGTH_LONG).show();
		else {
			SortSQL.insert(this, sort, number);
			adapter.add(sort);
		}
		db.close();
	}

	private void getContent(int id) {
		int selestItem = 0;
		String sort = null;
		Cursor c = NoteSQL.selectOne(this, id);
		c.moveToFirst();
		while (!c.isAfterLast()) {
			title.setText(c.getString(0));
			content.setText(c.getString(1));
			sort = c.getString(2);
			c.moveToNext();
		}

		DataBaseHelper helper = new DataBaseHelper(this, DataBaseInfo.DB_NAME,
				null, 1);
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor _sort = db.rawQuery("select * from " + DataBaseInfo.SORT_TABLE
				+ " order by _id desc", null);
		_sort.moveToFirst();
		while (!_sort.isAfterLast()) {
			if (sort != null && _sort.getString(1).equals(sort))
				break;
			selestItem++;
			_sort.moveToNext();
		}
		mSort.setSelection(selestItem);
		db.close();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, Nsave, Menu.NONE, "保存").setIcon(R.drawable.save);
		menu.add(0, Nlist, Menu.NONE, "转到礼品列表").setIcon(R.drawable.redo1);
		menu.add(0, mClose, Menu.NONE, "关闭").setIcon(R.drawable.close);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Nsave: {
			String t = title.getText().toString();
			String c = content.getText().toString();
			String s = mSort.getSelectedItem().toString();
			if (isEdit && t.trim().length() > 0 && c.trim().length() > 0
					&& s.length() > 0)
				NoteSQL.update(PresentEditDC.this, t, c, s, nid);
			else if (t.trim().length() > 0 && c.trim().length() > 0
					&& s.length() > 0) {
				NoteSQL.insert(PresentEditDC.this, t, c, s);
				Intent i = new Intent(this, PresentsListDC.class);
				startActivity(i);
				finish();
			} else
				Toast.makeText(PresentEditDC.this, "温馨提示：\n留言不能为空！",
						Toast.LENGTH_LONG).show();
			return true;
		}
		case Nlist: {
			Intent i = new Intent(this, PersonsListDC.class);
			startActivity(i);
			finish();
			return true;
		}
		case mClose:
			finish();
			return true;
		default:
			return false;
		}
	}

	private static final String[] PHONES_PROJECTION = new String[] {

	Phone.DISPLAY_NAME, Phone.NUMBER, Phone.CONTACT_ID };
}
